package com.wtb.thread;

import java.util.HashMap;
import java.util.concurrent.BlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.renren.api.client.RenrenApiClient;
import com.renren.api.client.param.impl.AccessToken;
import com.wtb.domain.Config;
import com.wtb.domain.DataCache;
import com.wtb.pub.WtbException;
import com.wtb.qq.domain.QqOauth;
import com.wtb.rr.domain.RrOauth;
import com.wtb.utils.DateUtils;
import com.wtb.utils.MessageUtils;

public class RrReadThread implements Runnable {
	private static final Log log = LogFactory.getLog(RrReadThread.class);
	private BlockingQueue<QqOauth> qqQueue;								//微博发送队列
	private BlockingQueue<RrOauth> traver_rrQueue;						//人人状态遍历队列
	private RenrenApiClient client = null;	
	private JSONObject source;											//新鲜事来源
	private String lastStatusTime;										//状态发布时间
	private String rrlastTime;											//人人状态上次被放入队列时间
	private RrOauth rrOauth = null;
	private JSONObject status = null;									//人人状态json
	private String messageString;										//人人状态内容
	private String image_url;											//图片地址
	private JSONArray attachment;										//包含照片的json数组
	private JSONObject photo;											//照片json
	private HashMap<String, QqOauth> qq_map;							//数据副本
	public RrReadThread(BlockingQueue<QqOauth> qqQueue,BlockingQueue<RrOauth> traver_rrQueue) {
		this.qqQueue = qqQueue;
		this.traver_rrQueue = traver_rrQueue;
	}

	public void run() {
		log.info("人人读线程已启动");
		while (true) {
			log.debug("*********"+Thread.currentThread().getName()+"在工作！*************");
			try {
				rrOauth = traver_rrQueue.take();
				client = RenrenApiClient.getInstance();
				org.json.simple.JSONArray feed =client.getFeedService().getFeed("10,30", Long.valueOf(rrOauth.getUni()), 1, 1, new AccessToken(rrOauth.getAccess_token()));
				if (!feed.isEmpty()) {
					status = (JSONObject) feed.get(0);
				}
			} catch (Exception e) {
				log.error("获取人人新鲜事失败：", e);
				throw new WtbException("获取人人新鲜事失败", e);
			}
			log.debug("新鲜事:"+status);
			if (status != null) {
				praseResult(status);
			}

		}
	}

	/**
	 * 解析返回JSON 判断是否要发送
	 * @param resultJson
	 */
	private void praseResult(JSONObject resultJson){
		lastStatusTime = (String) resultJson.get("update_time"); 	//格式为 2012-05-31 16:08:36
		if (resultJson.containsKey("source")) {					  	//包含来源
			source = (JSONObject) resultJson.get("source");
			for (int i = 0; i < Config.RR_FROM.length; i++) {
				if ((source.get("text").equals(Config.RR_FROM[i]))){
					return;
				}
			}
		}
		rrlastTime = DataCache.synRrTime(rrOauth.getUni());	 //格式为20120531161302
		//此新鲜事时间大于上次同步时间
		if (DateUtils.toMillins_(rrlastTime)/1000 < DateUtils.toMillins(lastStatusTime)/1000) {  
			putToQueue(resultJson);
		}
	}
	
	/**
	 * 生成微博发送队列
	 * @param rrOauth
	 * @param status
	 */
	@SuppressWarnings("unchecked")
	private void putToQueue(JSONObject status) {
		qq_map = DataCache.synQqMap();  					//取出此时的数据副本
		if (!qq_map.containsKey(rrOauth.getRef())) {
			return;
		}
		QqOauth qqOauth = qq_map.get(rrOauth.getRef());
		//上传图片新鲜事
		if ((Long)status.get("feed_type") == 30) {
			attachment = (JSONArray) status.get("attachment");
			if (attachment.size()>1) {
				return;     //上传多张照片 不去处理
			}else {
				photo = (JSONObject) attachment.get(0);
				image_url = (String) photo.get("raw_src");
				qqOauth.setImageUrl(image_url);
				if (photo.containsKey("content")) {  //包含描述内容
					qqOauth.setMessage((String)photo.get("content"));
				}else{
					qqOauth.setMessage("#分享照片#");
				}
			}
		}
		//状态新鲜事
		if ((Long)status.get("feed_type")==10) {
			messageString = (String) status.get("message");
			//包含@某人 "转自" 不转发
			if (MessageUtils.cotainString(messageString, "@,转自")) {
				return;
			}
			//以“-”结尾 不转发
			if (messageString.lastIndexOf("-")==messageString.length()-1) {
				return;
			}
			//大于140个汉字 不转发
			if (messageString.length() > 280) {
				return;
			}
			String mes = MessageUtils.rr2qqExpression(messageString);
			//过滤表情后为空 不转发
			if (mes == null || "".equals(mes)) {
				return;
			}
			qqOauth.setMessage(mes);
		}
		qqOauth.setLastTime((DateUtils.toDateString((String) status.get("update_time"))));
		try {
			qqQueue.put(qqOauth);
			log.debug("已加入qq微博发送队列");
		} catch (InterruptedException e) {
			log.error("放入微博队列失败：", e);
			throw new WtbException("放入微博队列失败", e);
		}
	}
}
